package com.hn658.base.message.notisender.sender.android;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.baidu.yun.channel.auth.ChannelKeyPair;
import com.baidu.yun.channel.client.BaiduChannelClient;
import com.baidu.yun.channel.exception.ChannelClientException;
import com.baidu.yun.channel.exception.ChannelServerException;
import com.baidu.yun.channel.model.PushUnicastMessageRequest;
import com.baidu.yun.core.log.YunLogEvent;
import com.baidu.yun.core.log.YunLogHandler;
import com.hn658.base.message.appinfo.entity.AppInfoEO;
import com.hn658.base.message.appinfo.service.IAppInfoService;
import com.hn658.base.message.common.enums.NotifySenderType;
import com.hn658.base.message.notisender.message.AndroidMessage;
import com.hn658.base.message.notisender.sender.AbstractMessageSender;
import com.hn658.framework.logging.enums.LogCategory;

/**
 * 
 * android百度推送
 * @author ztjie
 * @date 2015-10-22 下午1:44:33
 * @since
 * @version
 */
@Component("androidMessageSender")
public class AndroidMessageSender extends AbstractMessageSender<AndroidMessage> {
	
	@Autowired
	private IAppInfoService appInfoService;
    
    @Override
    public void send(AndroidMessage message) {
        ChannelKeyPair pair = null;
        AppInfoEO appInfo = appInfoService.findAppBaiduConfig(message.getAppId());
        pair = new ChannelKeyPair(appInfo.getBaiduApiKey(), appInfo.getBaiduSecretKey());
        BaiduChannelClient channelClient = new BaiduChannelClient(pair);

        channelClient.setChannelLogHandler(new YunLogHandler() {
            @Override
            public void onHandle(YunLogEvent event) {
                logger.debug(LogCategory.SYSTEM, event.getMessage());
            }
        });

        try {
            // 创建请求类对象
            PushUnicastMessageRequest request = new PushUnicastMessageRequest();
			request.setDeviceType(3); // device_type => 1: web 2: pc 3:android 4:ios 5:wp
            request.setChannelId(message.getChannelId());
            request.setUserId(message.getUserId());

            request.setMessageType(0);
            request.setMessage(message.getContent());

            // 调用pushMessage接口
            channelClient.pushUnicastMessage(request);
        } catch (ChannelClientException e) {
            // 处理客户端错误异常
            logger.error(LogCategory.SYSTEM, "处理客户端错误异常", e);
        } catch (ChannelServerException e) {
            // 处理服务端错误异常
            logger.error(LogCategory.SYSTEM, String.format("request_id: %d, error_code: %d, error_message: %s",
                    e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
        }
    }

	@Override
	public NotifySenderType getTarget() {
		return NotifySenderType.Android;
	}
	
}
